package com.real.fact.web.customer.application;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.globant.katari.core.application.Command;
import com.globant.katari.core.application.JsonRepresentation;
import com.real.fact.web.application.RealPaging;
import com.real.fact.web.customer.domain.Customer;
import com.real.fact.web.customer.domain.CustomerRepository;

public class SearchCustomerCommand implements Command<JsonRepresentation> {

  private final CustomerRepository customerRepository;

  private String query;

  public SearchCustomerCommand(final CustomerRepository theCustomerRepository) {
    customerRepository = theCustomerRepository;
  }

  public String getQuery() {
    return query;
  }

  public void setQuery(final String theQuery) {
    this.query = theQuery;
  }

  public JsonRepresentation execute() {
    try {
      List<Customer> result = customerRepository.findByName(query, new RealPaging());
      JSONObject resultSet = new JSONObject();
      JSONArray array = new JSONArray();
      for (Customer p : result) {
        JSONObject object = new JSONObject();
        object.put("id", p.getId());
        object.put("name", p.getName());
        object.put("cuil", p.getCuil());
        object.put("address", p.getAddress());
        object.put("contact", p.getContactInfo());
        array.put(object);
      }
      resultSet.put("Result", array);
      return new JsonRepresentation(resultSet);
    } catch (JSONException e) {
      throw new RuntimeException("Error searching customers", e);
    }
  }

}
